const app = getApp();
var home = require("../../utils/util.js");
var url = home.home;
var url2 = home.home2;
const defaultAvatarUrl = 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    currentDate: new Date().getTime(),
    minDate: -631180800000,
    maxDate: new Date().getTime(),
    formatter(type, value) {
      if (type === 'year') {
        return `${value}`;
      }
      if (type === 'month') {
        return `${value}`;
      }
      return value;
    },
    storeId: app.globalData.storeId, //店铺ID
    memberId:home.getKey('userId'),
    bgcolor:home.getKey('bgcolor'),
    dateShow:false,//生日开关
    sexShow:false,//性别开关
    birthday:home.getKey('birthday'),
    sexColumns:['保密','男','女'],
    sex:home.getKey('sex'),
    sexIndex:1,
    name:home.getKey('nickName'),
    nameShow:false,//名称开关
    temName:'',//临时会员名称
    phone:home.getKey('phone'),
    phoneShow:false,//手机号开关
    temPhone:'',//临时手机号
    sms:'',//验证码
    avatarUrl: home.getKey('avatar'),
    avatar:home.getKey('avatar')
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this;
    that.data.avatarUrl = home.getKey('avatar');
    console.log(that.data.avatarUrl);
  },

  /**
   * 选择-确认
   */
  confirm(e) {
    let data = {};
    data.memberId = home.getKey('userId');
    data.storeId = home.getKey('storeId');
    if (e.currentTarget.dataset.type == 'date') {
      let time = new Date(e.detail);
      let Y = time.getFullYear();
      let m = time.getMonth() + 1;
      let d = time.getDate() < 10 ? "0"+time.getDate() : time.getDate();
      m = m < 10 ? "0" + m : m;
      let birthday = Y + '-' + m + '-' + d;
      this.setData({
        currentDate: e.detail,
        birthday:birthday,
        dateShow:false
      });
      data.birthday = birthday;
    } else if (e.currentTarget.dataset.type == 'sex') {
      let sexIndex = 0;
      data.sex = '03';
      if (e.detail.value == '男') {
        data.sex = '01';
        sexIndex = 1;
      } else if (e.detail.value == '女') {
        data.sex = '02';
        sexIndex = 2;
      }
      this.setData({
        sexShow: false,
        sex:e.detail.value,
        sexIndex:sexIndex
      });
    } else if (e.currentTarget.dataset.type == 'name') {
      console.log("name");
      let temName = this.data.temName;
      this.setData({
        nameShow: false,
        name:temName
      });
      data.name = temName;
    } else if (e.currentTarget.dataset.type == 'phone') {
      let temPhone = this.data.temPhone;
      let myreg=/^[1][3,4,5,7,8,9][0-9]{9}$/;
      if (!myreg.test(temPhone)) {
        wx.showToast({
          title: '请填写正确的手机号',  // 标题
          icon: 'none',   // 图标类型，默认success
          duration: 1500   // 提示窗停留时间，默认1500ms
        });
        return false;
      }
      this.setData({
        phoneShow: false,
        phone:temPhone
      });
    }
    wx.request({
      url: url + 'app/updateUserNameInfo',
      data:this.data,
      method: 'POST',
      header: {
        "content-type": "application/json", // 默认
      },
      success:function (res) {
        if (res.data.code == 200) {
          if (data.name) {
            home.setKey('name',data.name);
          }
          if (data.birthday) {
            home.setKey('birthday',data.birthday);
          }
        } else {
          wx.showToast({
            title: '修改失败',
            icon: 'none'
          })
        }
      }
    })
  },

  /**
   * 弹出选择层
   */
  showPopup(e){
    if (e.currentTarget.dataset.type == 'date') {
      this.setData({ dateShow: true });
    } else if (e.currentTarget.dataset.type == 'sex') {
      this.setData({ sexShow: true });
    } else if (e.currentTarget.dataset.type == 'name') {
      this.setData({ nameShow: true });
    } else if (e.currentTarget.dataset.type == 'phone') {
      this.setData({ phoneShow: true });
    }
  },

  /**
   * 关闭选择层
   */
  onClose(e) {
    if (e.currentTarget.dataset.type == 'date') {
      this.setData({ dateShow: false });
    } else if (e.currentTarget.dataset.type == 'sex') {
      this.setData({ sexShow: false });
    } else if (e.currentTarget.dataset.type == 'name') {
      this.setData({ nameShow: false,temName:"" });
    } else if (e.currentTarget.dataset.type == 'phone') {
      this.setData({ phoneShow: false,temPhone:"" });
    } else if (e.currentTarget.dataset.type == 'avatar') {
      this.setData({ avatarShow: false,temPhone:"" });
    }
  },

  /**
   * 修改名称
   */
  onChange(e){
    console.log(e);
    console.log("222");
    if (e.currentTarget.dataset.type == 'name') {
      this.setData({temName:e.detail.value});
      this.saveName({storeId:app.globalData.storeId,memberId:home.getKey('userId'),name:e.detail.value});
    } else if (e.currentTarget.dataset.type == 'phone') {
      this.setData({temPhone:e.detail});
    }
    else if (e.currentTarget.dataset.type == 'avatar') {
      this.setData({avatar:e.detail.value});
      this.saveAvatar({storeId:app.globalData.storeId,memberId:home.getKey('userId'),avatar:e.detail.value});
    }
  },
  /**
   * 保存数据
   */
  save(data){
    console.log("save");
    wx.request({
      url: url + 'app/updateUserNameInfo',
      data:data,
      method: 'POST',
      header: {
        "content-type": "application/json", // 默认
      },
      success:function (res) {
        if (res.data.code == 200) {
          if (data.name) {
            home.setKey('name',data.name);
          }
          if (data.birthday) {
            home.setKey('birthday',data.birthday);
          }
        } else {
          wx.showToast({
            title: '修改失败',
            icon: 'none'
          })
        }
      }
    })
  },
  /**
   * 保存头像
   */
  saveAvatar(data){
    console.log("save");
    wx.request({
      url: url + 'app/updateUserAvatar',
      data:data,
      method: 'POST',
      header: {
        "content-type": "application/json", // 默认
      },
      success:function (res) {
        if (res.data.code == 200) {
          if (data.avatar) {
            home.setKey('avatar',data.avatar);
          }
        } else {
          wx.showToast({
            title: '修改失败',
            icon: 'none'
          })
        }
      }
    })
  },
  /**
   * 保存姓名
   */
  saveName(data){
    console.log("save");
    wx.request({
      url: url + 'app/updateUserName',
      data:data,
      method: 'POST',
      header: {
        "content-type": "application/json", // 默认
      },
      success:function (res) {
        if (res.data.code == 200) {
          if (data.name) {
            home.setKey('name',data.name);
          }
        } else {
          wx.showToast({
            title: '修改失败',
            icon: 'none'
          })
        }
      }
    })
  },

  /**
   * 调起手机相册
   */
  chooseimage() {
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success (res) {
        // tempFilePath可以作为img标签的src属性显示图片
        const tempFilePaths = res.tempFilePaths
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let currentDate = new Date(home.getKey('birthday'));
    currentDate = currentDate.getTime();

    let sexIndex = 0;
    if (home.getKey('sex') == '男') {
      sexIndex = 1;
    } else if (home.getKey('sex') == '女') {
      sexIndex = 2;
    }
    this.setData({
      currentDate:currentDate,
      birthday:home.getKey('birthday'),
      sexIndex:sexIndex,
      sex:home.getKey('sex'),
      name:home.getKey('nickName'),
      avatar:home.getKey('avatar'),
      avatarUrl:home.getKey('avatar'),
    });
  },
  login() {
    let that = this;
    wx.getUserProfile({
        desc: '用于完善会员资料',
        success: function (ress) {
            wx.login({
                success: function name(res) {
                    wx.request({
                        url: url + 'app/xcx/updateUserNickName?storeId=' + app.globalData.storeId + '&code=' + res.code + '&nickName=' + ress.userInfo.nickName + '&headPortrait=' + ress.userInfo.avatarUrl + '&sex=保密' + '&unionId=' + home.getKey('unionId') + '&xcxOpenId=' + home.getKey('openId'),
                        data: {
                            code: res.code,
                            storeId: app.globalData.storeId,
                            nickName: ress.userInfo.nickName,
                            avatar:ress.userInfo.avatarUrl,
                            name:ress.userInfo.nickName,
                            headPortrait: ress.userInfo.avatarUrl,
                            sex: '保密',
                            xcxOpenId: home.getKey('openId'),
                            unionId: home.getKey('unionId'),
                        },
                        method: 'POST',
                        header: {
                            "content-type": "application/json", // 默认
                        },
                        success: function (rea) {
                            if (rea.data.code == 200) {
                                wx.hideLoading({
                                    success: (res) => {},
                                })
                                home.setKey('state', 2);
                            }
                        }
                    })
                }
            })
        },
        fail: function (params) {
            that.setData({
                states: false,
            });
            that.getTabBar().setData({
                btnState: true,
            });
        }
    })
},
  //退出登录
  close(){
    wx.clearStorage();
    try {
      wx.reLaunch({
        url: '../../pages/index/index',
      })
    } catch(e) {
      // Do something when catch error
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },
//获取到api返回的新地址路径
onChooseAvatar(e) {
  const { avatarUrl } = e.detail 
  console.log("avatarUrl:"+avatarUrl);
    this.setData({
      avatarUrl,
    })
    const { avatar } = e.detail 
    this.setData({
      avatar,
    })
    this.upLoadImage();
},
//上传图片的函数
upLoadImage(){
  var that=this;
  console.log("url:"+url + 'sys/common/upload');
  console.log(that.data.avatarUrl);
  wx.uploadFile({//调用微信里面上传文件的开放接口
    url: url + 'sys/common/upload', //上传到服务器的接口
    filePath:that.data.avatarUrl,//文件的路径，只能有一个，不支持数组等一次性包含多个文件路径的形式
    header: {
      "Content-Type": "multipart/form-data"
    },
    name: 'file',//接口文档中给该文件的字段名
    formData:{
      user: 'test'
    },//这里面写除了文件外的其他参数
    success: (result) => {
          var resObject=result.data;
          var jsonObject = JSON.parse(resObject);
          if(result.statusCode==200){
            this.saveAvatar({storeId:app.globalData.storeId,memberId:home.getKey('userId'),avatarUrl:"https://kyz.fbhkj.com/"+jsonObject.message});
            home.setKey('avatar',"https://kyz.fbhkj.com/"+jsonObject.message);
            that.data.avatarUrl = "https://kyz.fbhkj.com/"+jsonObject.message;
            wx.switchTab({
              url: '/shop/userInfo/index',//url: 'shop/userInfo/index',
            })
          }else{
          }
       },
       fail:function(){
        wx.navigateBack({
          delta: 1,
        })
       }
  })
},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})